package com.smsc.headend.connector.utils;

import com.smsc.headend.connector.netty.decoder.DecodeProxy;
import io.netty.channel.Channel;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.Attribute;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

@Slf4j
public class NetUtil {

    public static String getIpFromChannel(Channel channel) {
        if (channel == null) {
            return null;
        }

        if (channel.getClass().isAssignableFrom(EmbeddedChannel.class)) {
            return "localhost-domain";
        }

        if (!channel.getClass().isAssignableFrom(InetSocketAddress.class) && !channel.getClass().isAssignableFrom(NioSocketChannel.class)) {
            log.error("Channel Type: {}", channel.getClass());
            return null;
        }
        Attribute<String> channelAttr = channel.attr(DecodeProxy.key);
        //基于channel的属性
        if (null != channelAttr.get()) {
            return channelAttr.get();
        }
        InetSocketAddress address = (InetSocketAddress) channel.remoteAddress();
        return address.getAddress().getHostAddress() + ":" + address.getPort();
    }


    public static int getLocalPort(Channel channel) {
        if (channel == null) {
            return -1;
        }

        if (channel.getClass().isAssignableFrom(EmbeddedChannel.class)) {
            return 6602; //使用EmbeddedChannel本地测试，使用默认本地端口
        }

        if (!channel.getClass().isAssignableFrom(InetSocketAddress.class) && !channel.getClass().isAssignableFrom(NioSocketChannel.class)) {
            log.error("Channel Type: {}", channel.getClass());
            return -1;
        }
        InetSocketAddress socketAddress = (InetSocketAddress) channel.localAddress();
        if (socketAddress == null) {
            return -1;
        }
        return socketAddress.getPort();
    }
}
